<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </page-filter>
      </div>
      <div class="filter-wrapper">
        <page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-check>
            <el-button :disabled="!canCheck" @click="check()">审核</el-button>
          </template>
          <template v-slot:filter-reject>
            <el-button :disabled="!canReject" @click="reject()">驳回</el-button>
          </template>
        </page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <!--<template v-slot:col-licenseNum="scope">
          <span class="slip-edit" @click="openDetail(scope.row)">{{scope.row.licenseNum}}</span>
        </template>-->
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>

    <contract-modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <contract-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="pendCheckContract">
import PageFilter from '@/components/NewPageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import {
  checkContract,
  rejectContract,
  getSpdContractCustomizeListPage,
} from '@/api/contract.js'
import ContractModify from './modify'
import ContractDetail from './details'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

import _ from 'lodash'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const detailList = defineAsyncComponent(() => import('./detailList'))
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)

// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      dataSource: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 2,
      },
    },
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'check',
      abel: '审核',
      show: proxy.$permission('pendCheckContract:check'),
    },
    {
      type: 'slot',
      value: 'reject',
      label: '驳回',
      show: proxy.$permission('pendCheckContract:reject'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('pendCheckContract:update'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '审核',
        event: check,
        show: proxy.$permission('pendCheckContract:check'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('pendCheckContract:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
    ],
  },
})
const modifyInfo = reactive({
  visible: false,
  id: '',
  title: '',
})
const detailListInfo = reactive({
  visible: false,
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const paramsFlag = ref(true)

const canCheck = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 2).length
  )
})
const canReject = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 2).length
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function() {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'pendCheckContract' && el.url === val.url) {
                modifyInfo.visible = false
                detailInfo.visible = false
                detailListInfo.visible = false
                advancedSearchInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})

onDeactivated(() => {
  stopWatch()
})

watch(
  () => tableInfo.data,
  () => {
    const params = proxy.$route.params
    if (params && params.orderId && paramsFlag.value) {
      const item = _.find(tableInfo.data, ['orderNo', params.orderId])
      sessionStorage.setItem('storeRowId', item.id)
      paramsFlag.value = false
    }
  }
)

let obj = {
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'contract_type',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'contract_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

onMounted(() => {
  const params = proxy.$route.params
  if (params && params.orderId) {
    openDetails(params.orderId)
  }
})

//驳回
function reject(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  rejectContract(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//审核
function check(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  checkContract(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页

  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}

function update(row) {
  //修改
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.id = row.id
  modifyInfo.title = '修改'
  modifyInfo.visible = true
}

//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.id = row.id
  detailInfo.visible = true
}
function openDetails(id) {
  detailInfo.id = id
  detailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(slipSelectRequest = true) {
  let param = {
    tableKey: 'pendContractList-com.slip.spd.entity.vo.contract.ContractVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest = slipSelectRequest
      tableInfo.api = getSpdContractCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
